package com.guigu.gulicommon.context;


import cn.hutool.core.util.StrUtil;
import lombok.extern.log4j.Log4j2;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户拦截器
 * <p>
 * 本类用于拦截用户信息，将用户信息存入ThreadLocal
 *
 * @author 陈俊杰
 * @version 1.0
 * @since 2024/8/14 19:02
 */
@Log4j2
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {   //  controller之前执行
        //  1.获取用户信息
        //  和网关保持一致
        String userId = request.getHeader("gulimall-userId");
        //  2.判断是否获取了用户，如果有，存入ThreadLocal
        //3 设置token
        String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token) && StrUtil.isNotBlank(userId)) {
            UserContext.getInstance().setCurrentUser(userId, token);
        }
        //  3.放行
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        //  controller完成之后
        //  清理用户
        UserContext.getInstance().clear();
        log.info("用户请求线程已销毁");
    }
}
